Puzzle 17 Explanation: String Conversion
Understand how to perform string conversions in Go.
We'll cover the following
Try it yourself#
Try running the code below to see the result for yourself.
Implementing int conversion to string
Explanation#
The string type supports type conversion from int. It’ll treat this integer as a
rune. The rune 169 is the copyright sign (©). This mistake is usually common in languages such as Python where str(169) → "169".
To convert a number to a string (or a string to a number), use the
strconv package.
Testing how int can be converted to a string by using strconv
Strings also support type conversion from a byte slice.
int conversion to string by using byte slice
When we convert from a byte slice to a string, Go copies the byte slice, then performs a memory allocation. In maps, where we can’t use a []byte as a
key, there is a compiler optimization.
Implementing int conversion to string using map
Puzzle 17: An **Int**eresting String
Puzzle 18: A Job to Do